package com.gulimall.product.service.impl;

import com.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.product.dao.CategoryDao;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成树形父子结构
        //2.1找到所有的一级分类
        List<CategoryEntity> catLevel = entities.stream().filter(categoryEntity ->
                categoryEntity.getCatLevel() == 1
        ).map((menu) ->{
            menu.setChildren(getChildrens(menu,entities));//当前菜单的子分类
            return menu;
        }).sorted((menu1,menu2)->{//给当前映射好的菜单排序
            return (menu1.getSort() == null ?0:menu1.getSort()) - (menu2.getSort() == null ?0:menu2.getSort());
        }).collect(Collectors.toList());
        return catLevel;
    }

    /**
     * 删除分类
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> parentPath = findParentPath(catelogId, new ArrayList<Long>());
        Collections.reverse(parentPath);
        return  parentPath.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return  递归获取某个菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //如果遍历的当前菜单父分类id 等于 要查找菜单的id就是root菜单下的子菜单
                //return categoryEntity.getParentCid() == root.getCatId();
            return (categoryEntity.getParentCid().longValue() == root.getCatId().longValue());
        }).map((categoryEntity)->{
            //找到的菜单下面可能还会有子菜单，继续递归查找
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //菜单排序
            return (menu1.getSort() == null ?0:menu1.getSort()) - (menu2.getSort() == null ?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}